package com.ruoyi.system.wnjk.consumer;

import com.ruoyi.system.wnjk.config.ReceiveItemMQConfig;
import com.ruoyi.system.wnjk.contents.Contents;
import com.ruoyi.system.wnjk.domain.po.ShopOrder;
import com.ruoyi.system.wnjk.service.IShopOrderService;
import com.ruoyi.system.wnjk.producer.ReceiveItemProducer;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ReceiveItemConsumer {

    @Autowired
    private IShopOrderService shopOrderService;

    @Autowired
    private ReceiveItemProducer receiveItemProducer;

    /**
     * 消费消息
     * @param orderId
     */
    @RabbitListener(queues = ReceiveItemMQConfig.AUTO_CONFIRM_QUEUE_NAME)
    public void processAutoConfirm(String orderId) {
        System.out.println("订单到期，自动收货 : " + orderId);

        try {
            confirmOrder(orderId);
        } catch (Exception e) {
            System.err.println("自动收货失败 Failed to confirm order: " + orderId);
            e.printStackTrace();
        }
    }

    /**
     * 自动确认收货
     * @param orderId
     */
    private void confirmOrder(String orderId) {
        // 实现具体的确认收货逻辑
        System.out.println("开始自动收货Auto confirming order: " + orderId);

        // 更新订单状态为已确认
        try {
            ShopOrder shopOrder = shopOrderService.selectShopOrderById(Long.parseLong(orderId));
            shopOrder.setStatus(Contents.Shop.ORDER_STATUS_SHIPPED_CONFIRMED);
            shopOrderService.updateShopOrder(shopOrder);
        }catch (Exception e){
            e.printStackTrace();
//            receiveItemProducer.createOrder(orderId);
        }
//        order.setStatus("CONFIRMED");
        System.out.println("自动收货结束 Order confirmed: " + orderId);
    }
}
